<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>元素拖拽示例</title>
    <style>
        body {
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100vh;
                margin: 0;
                background-color: #f0f0f0;
        }


        .draggable {
            width: 100px;
            height: 100px;
            background-color: #3498db;
            border-radius: 50%;
            color: #FFF;
            text-align: center;
            line-height: 100px;
            cursor: grab;
            user-select: none;
            position: absolute;
        }

    </style>
</head>
<body>
    <div class="draggable" id="draggableElement"></div>
    <script>
        const draggableElement = document.getElementById('draggableElement');
        let offsetx , offsety;
        let isDragging = false;


        draggableElement.addEventListener('mousedown', (e) => {
            isDragging = true;
            offsetx = e.clientX - draggableElement.getBoundingClientRect().left;
            offsety = e.clientY - draggableElement.getBoundingClientRect().top;
            draggableElement.style.cursor = 'grabbing';
        });


        document.addEventListener('mousemove', (e) => {
            if(isDragging) {
                const newX = e.clientX - offsetx;
                const newY = e.clientY - offsety;
                draggableElement.style.left = newX + 'px';
                draggableElement.style.top = newY + 'px';
            }    
        })

        document.addEventListener('mouseup', () => {
            isDragging = false;
            draggableElement.style.cursor = 'grab';
        })
   </script>     
</body>
</html>